import {Button, Modal} from 'antd'
import React, {useState, useEffect} from 'react'
import {PlusOutlined} from '@ant-design/icons'
import type {ColumnsType} from 'antd/es/table'
import CustomTable from '@/components/Table'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import {getCompany, getOrgUserList} from '@/service/common'
import {translateDataToTree} from '@/utils/common'

interface DataType {
	userId: number
	userName: string
	positionName: string
	phone?: string
	orgName?: string
	orgId?: number
	departmentName?: string
}

const formItemLayout = {
	labelCol: {flex: '90px'},
	wrapperCol: {flex: '1'},
}
type propsType = {
	type: string
	data: any[]
	setDataList: React.Dispatch<any>
}

const participantsTable = (props: propsType) => {
	const {type, data, setDataList} = props
	const [total, setTotal] = useState<number>()
	const [modalTotal, setModalTotal] = useState()
	const [loading, setLoading] = useState(false)
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [modalParams, setModalParams] = useState({
		current: 1,
		size: 10,
	})
	const [orgUserList, setOrgUserList] = useState<any[]>([])
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [tableData, setTableData] = useState<any[]>([])
	const [selectData, setSelectData] = useState<any[]>([])
	const [orgSource, setOrgSource] = useState<any>([])
	const [searchData, setSearchData] = useState({})

	useEffect(() => {
		setSelectData(data)
	}, [data])
	useEffect(() => {
		if (isModalOpen) {
			setSearchData({})
			setModalParams({
				current: 1,
				size: 10,
			})
		}
	}, [isModalOpen])

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
			}
		})
	}
	useEffect(() => {
		onOrgFun()
	}, [])

	/** 获取人员列表 */
	const getOrgUserData = () => {
		setLoading(true)
		getOrgUserList({...modalParams, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setOrgUserList(res?.data.records)
					setModalTotal(res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setOrgUserList([])
				setLoading(false)
			})
	}
	useEffect(() => {
		getOrgUserData()
	}, [modalParams])

	/** 选择的列表分页 */
	useEffect(() => {
		const num = (params.current - 1) * params.size
		const datas = data?.slice(num, params.current * params.size)
		if (datas?.length === 0 && params.current !== 1) {
			setParams({
				current: params.current - 1,
				size: params.size,
			})
		}
		setTableData(datas)
	}, [params, data])
	useEffect(() => {
		setTotal(data?.length)
	}, [data])

	const columns: ColumnsType<DataType> = [
		{
			title: '人员姓名',
			dataIndex: 'username',
			align: 'center',
			width: 100,
		},
		{
			title: '联系方式',
			dataIndex: 'phone',
			align: 'center',
			width: 150,
		},
		{
			title: '人员职位',
			dataIndex: 'positionName',
			align: 'center',
			width: 120,
		},
		{
			title: '所属公司',
			dataIndex: 'orgName',
			align: 'center',
			width: 150,
		},
		{
			title: '所属部门',
			dataIndex: 'departmentName',
			align: 'center',
			width: 150,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 80,
			render: (text: any, record) => (
				<Button
					type="link"
					onClick={() => {
						const newData = selectData?.filter(
							(item: any) =>
								(item?.userId === record?.userId &&
									item?.orgId !== record?.orgId) ||
								item?.userId !== record?.userId,
						)
						setDataList(newData)
						setSelectData(newData)
					}}>
					删除
				</Button>
			),
		},
	]
	const viewColumns: ColumnsType<DataType> = [
		{
			title: '人员姓名',
			dataIndex: 'username',
			align: 'center',
			width: 100,
		},
		{
			title: '联系方式',
			dataIndex: 'phone',
			align: 'center',
			width: 150,
		},
		{
			title: '人员职位',
			dataIndex: 'positionName',
			align: 'center',
			width: 120,
		},
		{
			title: '所属公司',
			dataIndex: 'orgName',
			align: 'center',
			width: 150,
		},
		{
			title: '所属部门',
			dataIndex: 'departmentName',
			align: 'center',
			width: 150,
		},
	]

	const editCar = (record: any, types: string) => {
		if (types === 'add') {
			const newData = [...selectData]
			newData.push({
				...record,
			})
			setSelectData(newData)
		} else {
			const newData = selectData?.filter(
				(item: any) =>
					(item?.userId === record?.userId &&
						item?.orgId !== record?.orgId) ||
					item?.userId !== record?.userId,
			)
			setSelectData(newData)
		}
	}

	const modalcolumns: ColumnsType<DataType> = [
		{
			title: '人员姓名',
			dataIndex: 'username',
			align: 'center',
			width: 100,
		},
		{
			title: '联系方式',
			dataIndex: 'phone',
			align: 'center',
			width: 150,
		},
		{
			title: '人员职位',
			dataIndex: 'positionName',
			align: 'center',
			width: 120,
		},
		{
			title: '所属公司',
			dataIndex: 'orgName',
			align: 'center',
			width: 150,
		},
		{
			title: '所属部门',
			dataIndex: 'departmentName',
			align: 'center',
			width: 150,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 80,
			render: (text: any, record) => {
				const userData = selectData?.find(
					(item: any) =>
						item?.userId === record?.userId &&
						item?.orgId === record?.orgId,
				)
				return (
					<>
						{userData ? (
							<Button
								type="link"
								onClick={() => editCar(record, 'cancel')}>
								取消
							</Button>
						) : (
							<Button
								type="link"
								onClick={() => editCar(record, 'add')}>
								选择
							</Button>
						)}
					</>
				)
			},
		},
	]

	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '人员名称',
					name: 'username',
					key: 'username',
				},
				{
					type: 'input',
					label: '联系方式',
					name: 'phone',
					key: 'phone',
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'treeSelect',
					label: '所属公司',
					name: 'orgId',
					key: 'orgId',
					keys: 'id',
					title: 'name',
					treeData: orgSource,
				},
				{},
			],
		},
	]
	const onFinish = (values: any) => {
		setSearchData(values)
		setModalParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setModalParams({
			current: 1,
			size: 10,
		})
	}

	const handleOk = () => {
		setDataList(selectData)
		setIsModalOpen(false)
	}

	return (
		<div className={styles.participantsTable}>
			{type !== 'view' && type !== 'process' ? (
				<div className={styles.title}>
					<Button
						icon={<PlusOutlined />}
						type="primary"
						ghost
						size="small"
						style={{marginBottom: '24px'}}
						onClick={() => {
							setIsModalOpen(true)
						}}>
						选择盘点参与人
					</Button>
				</div>
			) : (
				''
			)}
			<CustomTable
				params={params}
				columns={
					type === 'view' || type === 'process'
						? viewColumns
						: columns
				}
				total={total}
				pagination
				callback={(pagination: any) => {
					setParams(pagination)
				}}
				loading={loading}
				dataSource={tableData}
			/>
			<Modal
				width={700}
				title="选择盘点参与人"
				destroyOnClose
				open={isModalOpen}
				onOk={handleOk}
				onCancel={() => setIsModalOpen(false)}
				className={styles.participantsMoadal}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
						btnStatus={false}
					/>
				</div>
				<CustomTable
					params={modalParams}
					columns={modalcolumns}
					total={modalTotal}
					pagination
					callback={(pagination: any) => {
						setModalParams(pagination)
					}}
					loading={loading}
					dataSource={orgUserList}
				/>
			</Modal>
		</div>
	)
}

export default participantsTable
